#!BPY

""" Registration info for Blender menus:
Name: 'OpenGL 1.0'
Blender: 232
Group: 'Export'
Submenu: 'All Meshes...' all
Submenu: 'Selected objects...' selected
Tooltip: 'Export selected mesh to OpenGL File (*.h)'
"""

# +---------------------------------------------------------+
# | Copyright (c) 2004 Justin L. Boss                       |
# | http://www.alt-network.com                              |
# | justin@alt-network.com                                  |
# | Aprl 8, 2004                                            |
# +---------------------------------------------------------+

import Blender
from Blender import *
from math import *


class Export:
	def __init__(self, filename):
		self.file = open(filename, "wb")

	def closefile(self):
			self.file.close()
#End
			
	def ExportFile(self, mesh, meshname, obj):
		images = []
		gltype = len(mesh.faces[0].v)
		self.file.write("/***************************************************************************\n")
		self.file.write(" *   Copyright (C) 2008 by Justin L. Boss                                  *\n")
		self.file.write(" *   justin@rtechguys.com                                                  *\n")
		self.file.write(" *                                                                         *\n")
		self.file.write(" *   This program is free software; you can redistribute it and/or modify  *\n")
		self.file.write(" *   it under the terms of the GNU General Public License as published by  *\n")
		self.file.write(" *   the Free Software Foundation; either version 2 of the License, or     *\n")
		self.file.write(" *   (at your option) any later version.                                   *\n")
		self.file.write(" *                                                                         *\n")
		self.file.write(" *   This program is distributed in the hope that it will be useful,       *\n")
		self.file.write(" *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n")
		self.file.write(" *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n")
		self.file.write(" *   GNU General Public License for more details.                          *\n")
		self.file.write(" *                                                                         *\n")
		self.file.write(" *   You should have received a copy of the GNU General Public License     *\n")
		self.file.write(" *   along with this program; if not, write to the                         *\n")
		self.file.write(" *   Free Software Foundation, Inc.,                                       *\n")
		self.file.write(" *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n")
		self.file.write(" ***************************************************************************/\n\n\n")
		self.file.write("void %s(" %meshname)
		for i in range(len(mesh.faces)):
			image = str(mesh.faces[i].image)[8:str(mesh.faces[i].image).find(".")]
			if (image not in images) and (image != ""):
				images.append (image)
		for image in images:
			self.file.write("unsigned int %sTex, " %image)
		self.file.write(")\n{\n")
		if str(mesh.faces[0].image) != "None": 
			self.file.write ("\tglBindTexture(GL_TEXTURE_2D, %sTex);\n" %str(mesh.faces[0].image)[8:str(mesh.faces[0].image).find(".")])
			CurrentImage = str(mesh.faces[0].image)
		else:
			CurrentImage = "None"
		if gltype == 3:
			self.file.write("\tglBegin(GL_TRIANGLES);\n")
		if gltype == 4:
			self.file.write("\tglBegin(GL_QUADS);\n")

		for i in range(len(mesh.faces)):
			if str(mesh.faces[i].image) != CurrentImage:
				if str(mesh.faces[i].image) != "None":
					self.file.write("\tglEnd();\n\n")
					self.file.write ("\tglBindTexture(GL_TEXTURE_2D, %sTex);\n" %str(mesh.faces[i].image)[8:str(mesh.faces[i].image).find(".")])
					if len(mesh.faces[i].v) == 3:
						self.file.write("\tglBegin(GL_TRIANGLES);\n")
					else:
						self.file.write("\tglBegin(GL_QUADS);\n")
				CurrentImage = str(mesh.faces[i].image)
				gltype = len(mesh.faces[i].v)

			if len(mesh.faces[i].v) == 3:
				if gltype != 3:
					self.file.write("\tglEnd();\n\n")
					self.file.write("\tglBegin(GL_TRIANGLES);\n")
				if mesh.faces[i].smooth == 0:
					self.file.write("\t\tglNormal3f(%f,%f,%f); " %(round(mesh.faces[i].no[0],5), round(mesh.faces[i].no[1],5), round(mesh.faces[i].no[2],5)))
				else:
				  self.file.write("\t\t")
				for j in range(len(mesh.faces[i].v)):
					if CurrentImage != "None":
						self.file.write("glTexCoord2f(%f,%f); " %(round(mesh.faces[i].uv[j][0],5), -round(mesh.faces[i].uv[j][1],5)))
					vx, vy, vz = mesh.verts[mesh.faces[i].v[j].index].co
					nx, ny, nz = mesh.verts[mesh.faces[i].v[j].index].no
					if mesh.faces[i].smooth != 0:
						self.file.write("glNormal3f(%f,%f,%f); " %(round(nx,5), round(ny,5), round(nz,5)))
					self.file.write("glVertex3f(%f,%f,%f); " %(round(vx,5), round(vy,5), round(vz,5)))
				self.file.write("\n")
				#print mesh.verts[mesh.faces[i][1].index].no[0]
			if len(mesh.faces[i].v) == 4:
				if gltype != 4:
					self.file.write("\tglEnd();\n\n")
					self.file.write("\tglBegin(GL_QUADS);\n")
				if mesh.faces[i].smooth == 0:
					self.file.write("\t\tglNormal3f(%f,%f,%f); " %(round(mesh.faces[i].no[0],5), round(mesh.faces[i].no[1],5), round(mesh.faces[i].no[2],5)))
				else:
				  self.file.write("\t\t")
				for j in range(len(mesh.faces[i].v)):
					if CurrentImage != "None": 
						self.file.write("glTexCoord2f(%f,%f); " %(round(mesh.faces[i].uv[j][0],5), -round(mesh.faces[i].uv[j][1],5)))
					vx, vy, vz = mesh.verts[mesh.faces[i].v[j].index].co
					nx, ny, nz = mesh.verts[mesh.faces[i].v[j].index].no
					if mesh.faces[i].smooth != 0:
						self.file.write("glNormal3f(%f,%f,%f); " %(round(nx,5), round(ny,5), round(nz,5)))
					self.file.write("glVertex3f(%f,%f,%f); " %(round(vx,5), round(vy,5), round(vz,5)))
				self.file.write("\n")

			gltype = len(mesh.faces[i].v)
		self.file.write("\tglEnd();\n}\n\n\n")
		Blender.Window.DrawProgressBar(1.0, '')
# End

	def All(self):
		scene = Blender.Scene.GetCurrent()
		objlist = scene.getChildren()
		for objects in objlist:
			if objects.getType() == 'Mesh':
				objname = objects.name
				meshname = objects.data.name
				mesh = Blender.NMesh.GetRaw(meshname)
				obj = Blender.Object.Get(objname)
				Export.ExportFile (self, mesh, meshname, obj)
				
	def Selected(self):
		objlist = Blender.Object.GetSelected()
		for objects in objlist:
			if objects.getType() == 'Mesh':
				objname = objects.name
				meshname = objects.data.name
				mesh = Blender.NMesh.GetRaw(meshname)
				obj = Blender.Object.Get(objname)
				Export.ExportFile (self, mesh, meshname, obj)
#End

	def Seleted(self):
		objects = Blender.Object.GetSelected()
		objname = objects[0].name
		meshname = objects[0].data.name
		mesh = Blender.NMesh.GetRaw(meshname)
		Export.GetImages(self, objects)
		Export.ExportFile (self, mesh, meshname)
#End

def fs_callback(filename):
	if filename.find('.h', -2) <= 0: filename += '.h'
	OpenGL = Export (filename)
	arg = __script__['arg']
	if arg == 'all':
		OpenGL.All()
	if arg == 'selected':
		OpenGL.Selected()
	OpenGL.closefile()

Blender.Window.FileSelector(fs_callback, "OpenGL Export")